<template>
  <a-spin :spinning="confirmLoading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol" name="CAcceptanceRecordForm">
          <a-row>
            <a-col :span="12">
              <a-form-item label="项目" v-bind="validateInfos.projectId" id="CAcceptanceRecordForm-projectId" name="projectId">
                <a-select
                  placeholder="请选择"
                  style="width: 100%"
                  v-model:value="formData.projectId"
                  :showSearch="true"
                  :options="projectList"
                  optionFilterProp="label"
                  @change="loadSubProjectList"
                ></a-select>
              </a-form-item>
            </a-col>

            <a-col :span="12" v-if="delSubProject ===false">
              <a-form-item label="子项目" v-bind="validateInfos.subProjectId" id="CAcceptanceRecordForm-subProjectId" name="subProjectId">
                    <a-select
                      :disabled="disabledFlag"
                      placeholder="请选择子项目"
                      style="width: 100%"
                      v-model:value="formData.subProjectId"
                      :showSearch="true"
                      :options="subProjectList"
                      optionFilterProp="label"
                    ></a-select>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="验收标题" v-bind="validateInfos.title" id="CAcceptanceRecordForm-title" name="title">
                <a-input  :disabled="disabledFlag" v-model:value="formData.title" placeholder="请输入验收标题"  allow-clear ></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="验收时间" v-bind="validateInfos.acceptanceTime" id="CAcceptanceRecordForm-acceptanceTime" name="acceptanceTime">
                <a-date-picker  :disabled="disabledFlag" placeholder="请选择验收时间"  v-model:value="formData.acceptanceTime" value-format="YYYY-MM-DD"  style="width: 100%"  allow-clear />
              </a-form-item>
            </a-col>

            <a-col :span="12">
              <a-form-item label="维保天数" v-bind="validateInfos.safeguardDay" id="CAcceptanceRecordForm-safeguardDay" name="safeguardDay">
                <a-input-number  :disabled="disabledFlag" v-model:value="formData.safeguardDay" placeholder="请输入维保天数" style="width: 100%" />
              </a-form-item>
            </a-col>

            <a-col :span="12">
              <a-form-item label="附件" v-bind="validateInfos.fileRecordId" id="CAcceptanceRecordForm-fileRecordId" name="fileRecordId">
                <j-upload :disabled="disabledFlag" v-model:value="formData.fileRecordId"   ></j-upload>
              </a-form-item>
            </a-col>

            <a-col :span="12">
              <a-form-item label="提交备注" v-bind="validateInfos.remark" id="CAcceptanceRecordForm-remark" name="remark">
                <a-textarea :disabled="disabledFlag" v-model:value="formData.remark" :rows="4" placeholder="请输入提交备注" />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row v-if="formData.acceptanceStatus==='审核中' ||  formData.acceptanceStatus==='驳回'  ">
            <a-divider >审核</a-divider >
            <a-col :span="24" v-if="formData.id">
              <a-form-item label="审核" v-bind="validateInfos.status" id="CAcceptanceRecordForm-status" name="status">
                <j-dict-select-tag type='radio' v-model:value="formData.status" dictCode="Audit" placeholder="请选择"  allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="审核描述" v-bind="validateInfos.reviewDescription" id="CAcceptanceRecordForm-reviewDescription" name="reviewDescription">
                <a-textarea v-model:value="formData.reviewDescription" :rows="4" placeholder="请输入审核描述" />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </template>
    </JFormContainer>
  </a-spin>
</template>

<script lang="ts" setup>
import { ref, reactive, defineExpose, nextTick, defineProps, computed, onMounted } from 'vue';
import { defHttp } from '/@/utils/http/axios';
import { useMessage } from '/@/hooks/web/useMessage';
import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
import JUpload from '/@/components/Form/src/jeecg/components/JUpload/JUpload.vue';
import { getValueType } from '/@/utils';
import { saveOrUpdate } from '../CAcceptanceRecord.api';
import { Form } from 'ant-design-vue';
import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
import { getProjectList, getSubProjectList } from '@/views/common.api';
const props = defineProps({
  formDisabled: { type: Boolean, default: false },
  formData: { type: Object, default: () => ({})},
  formBpm: { type: Boolean, default: true }
});
const formRef = ref();
const useForm = Form.useForm;
const disabledFlag =ref(false)
const emit = defineEmits(['register', 'ok']);
const formData = reactive<Record<string, any>>({
  id: '',
  acceptanceStatus: '',
  acceptanceTime: '',
  title: '',
  fileRecordId: '',
  projectId: undefined,
  subProjectId: undefined,
  acceptancePerson: '',
  remark: '',
  reviewerUserId: '',
  reviewTime: '',
  reviewDescription: '',
  log: '',
  safeguardDay: '',
});
const { createMessage } = useMessage();
const delSubProject = ref(false);
const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
const confirmLoading = ref<boolean>(false);
//表单验证
const validatorRules = reactive({
  title: [{ required: true, message: '请输入验收标题!'},],
  projectId: [{ required: true, message: '请输入项目!'},],
  safeguardDay: [{ required: true, message: '请输入维保天数!'},],
  acceptanceTime: [{ required: true, message: '请输入验收时间!'},],



});
const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });

// 表单禁用
const disabled = computed(()=>{
  if(props.formBpm === true){
    if(props.formData.disabled === false){
      return false;
    }else{
      return true;
    }
  }
  return props.formDisabled;
});


/**
 * 新增
 */
function add(record) {
  edit(record);
}

/**
 * 编辑
 */
function edit(record) {

  loadProjectList()
  if(record != undefined &&
    record.projectId != undefined &&
    record.projectId != null){
    loadSubProjectList(record.projectId);
  }
  delSubProject.value = false
  if(record !=null && record.projectId != '' && (record.subProjectId ==='' || record.subProjectId ===undefined)){
    delSubProject.value = true
  }
  disabledFlag.value = false;
  formData.status =""
  if(record.id && record.acceptanceStatus !="驳回"){
    disabledFlag.value = true;
  }
  if(formData.id && formData.acceptanceStatus ==="通过"){
    formData.status ="同意"
  }else if(formData.id && formData.acceptanceStatus ==="驳回"){
    formData.status ="驳回"
  }


  nextTick(() => {
    resetFields();
    const tmpData = {};
    Object.keys(formData).forEach((key) => {
      if(record.hasOwnProperty(key)){
        tmpData[key] = record[key]
      }

      if(key ==="acceptanceStatus"){
        if(record[key] ==="通过"){

          tmpData["status"] = "同意"
        }
        if(record[key] ==="驳回"){
          tmpData["status"] = "驳回"
        }
      }


    })
    //赋值
    Object.assign(formData, tmpData);
  });

}

/**
 * 提交数据
 */
async function submitForm() {

  if(formData.id && formData.status ==="同意"){
    formData.acceptanceStatus ="通过"
  }else if(formData.id && formData.status ==="驳回"){
    formData.acceptanceStatus ="驳回"
  }else {
    formData.acceptanceStatus =""
  }

  try {
    // 触发表单验证
    await validate();
  } catch ({ errorFields }) {
    if (errorFields) {
      const firstField = errorFields[0];
      if (firstField) {
        formRef.value.scrollToField(firstField.name, { behavior: 'smooth', block: 'center' });
      }
    }
    return Promise.reject(errorFields);
  }
  confirmLoading.value = true;
  const isUpdate = ref<boolean>(false);
  //时间格式化
  let model = formData;
  if (model.id) {
    isUpdate.value = true;
  }
  //循环数据
  for (let data in model) {
    //如果该数据是数组并且是字符串类型
    if (model[data] instanceof Array) {
      let valueType = getValueType(formRef.value.getProps, data);
      //如果是字符串类型的需要变成以逗号分割的字符串
      if (valueType === 'string') {
        model[data] = model[data].join(',');
      }
    }
  }
  await saveOrUpdate(model, isUpdate.value)
    .then((res) => {
      if (res.success) {
        createMessage.success(res.message);
        emit('ok');
      } else {
        createMessage.warning(res.message);
      }
    })
    .finally(() => {
      confirmLoading.value = false;
    });
}

/**
 * 加载 主项目下拉
 */
const projectList = ref([])
async function loadProjectList(){
  projectList.value = []
  projectList.value = await getProjectList()

}

/**
 * 加载 子主项目 下拉
 */
const subProjectList = ref([])
async function loadSubProjectList(projectId){
  formData.subProjectId=undefined
  subProjectList.value = []
  const params = {'projectId':projectId}
  subProjectList.value = await getSubProjectList(params)
}




defineExpose({
  add,
  edit,
  submitForm,
  delSubProject,
  loadProjectList,
  loadSubProjectList,
});
</script>

<style lang="less" scoped>
.antd-modal-form {
  padding: 14px;
}
</style>
